//
//  HttpClient.m
//  iphone-commons
//
//  Created by DizainStudio on 16.01.11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HttpClient.h"


@implementation HttpClient
@synthesize indicator, url, currentView, params;

-(id) initWithUrl:(NSString*) url withView: (UIView*) view {
	self.url = url;
	self.currentView = view;
}

-(id) initWithUrl:(NSString*) url withParams:(NSDictionary*) params withView: (UIView*) view {
	self.params = params;
	self.url = url;
	self.currentView = view;
}


-(void) showAlert {
	UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Невозможно соединиться с сервером" message:nil delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
	[alertView show];
	[alertView release];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
	[indicator removeFromSuperview] ;
	[self showAlert] ;
	[connection release];
	[responseData release];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	NSHTTPURLResponse *HTTPresponse = (NSHTTPURLResponse *)response;
	NSInteger statusCode = [HTTPresponse statusCode];
	if ( 404 == statusCode || 500 == statusCode ) {
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
		[indicator removeFromSuperview] ;
		[self showAlert] ;
		[connection cancel];
	} else {
		[responseData setLength:0];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
	[indicator removeFromSuperview] ;
	[self handleResult];
	[connection release];
}

// creates post request to url with string params
-(void) doRequest {
	// show indicator
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
	[currentView addSubview:indicator] ;
	indicator.center = CGPointMake(160, 240) ;
	
	// craete url
	NSURL *theURL = [NSURL URLWithString:[self getUrlWithParams]];

	NSLog([NSString stringWithFormat:@"Creating request to url: %@ with params: \n%@", url, [self createParams]]);
	NSMutableURLRequest *theRequest = [NSMutableURLRequest
									   requestWithURL:theURL
									   cachePolicy:NSURLRequestUseProtocolCachePolicy
									   timeoutInterval:10.0];
	[theRequest setHTTPMethod:[self getHttpMethod]];
	[theRequest setHTTPBody: [self getHttpBody]];
	
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest: theRequest 
																	 delegate: self];
	if (theConnection) {
		responseData = [[NSMutableData data] retain];
	} else {
		[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
		[indicator removeFromSuperview] ;
	}
}

/**
 * call dumpResult in handleResult implementation to log the result, received from server
 **/
-(void) dumpResult {
	NSString* result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
	NSLog([NSString stringWithFormat: @"handling result: \n%@", result]);
}

/**
 * do the stuff when successfull responce received
 * data from response is in responseData
 **/
-(void) handleResult{
}

/**
 * returns http method (GET, POST, etc)
 **/
-(NSString*) getHttpMethod {return NULL;}

/**
 * get url string from the request
 **/
-(NSString*) getUrlWithParams {return NULL;}

/**
 * get http body for the request
 **/
-(NSData*) getHttpBody {return NULL;}

/**
 * create params string from NSDictionary
 **/
-(NSString*) createParams {
	int i = 0;
	NSMutableString* paramsString = [[NSMutableString alloc] initWithString:@""];
	if (params != NULL) {
		for (NSString* key in [params allKeys]) {
			if (i > 0) {
				[paramsString appendString:@"&"];
			} else {
				i ++;
			}
			NSString* value = (NSString*) [params objectForKey:key];
			[paramsString appendString:[NSString stringWithFormat:@"%@=%@", key, value]];
		}
	}
	return paramsString;
}

@end
